package com.argrace.smart.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.WangGuanDeviceEntity;
import com.argrace.smart.model.LocalDb_RuoQiDeviceTable;
import com.argrace.smart.util.AlinkHttpUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/2/26.
 */

public class RuoQi_AddDeviceActivity extends BaseActivity {
    private EditText deviceName;
    private TextView deviceSeat,deviceType, deviceActions, relationDevice, relationDevice_text;
    private String deviceType_str, deviceActions_str, relationDevice_str;

    public Map<String, String> RUOQI_DEVICE_ACTIONS_DETAIL = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ruoqi_adddevice);
        init();
    }

    private void init() {

        setTitle(true, true, "添加设备");
        //进入设备修改保存状态界面
        showRight(true, R.mipmap.head_title_tick);
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }

        });
        setView();
        setData();
    }

    private void setData() {
        RUOQI_DEVICE_ACTIONS_DETAIL.put("switch", "[\"on\", \"off\"]");
        RUOQI_DEVICE_ACTIONS_DETAIL.put("mode", "[ \"auto\", \"manual\", \"cool\", \"heat\", \"dry\", \"fan\", \"silent\", \"energy\", \"sleep\" ]");
        RUOQI_DEVICE_ACTIONS_DETAIL.put("position", " [ \"up\",\"down\",\"num\" ]");//"up": 如：窗帘打开一点"down": 如：窗帘关闭一点"num": 如：窗帘打开/关闭到百分之几
        RUOQI_DEVICE_ACTIONS_DETAIL.put("fanspeed", "[ \"up\", \"down\", \"max\", \"min\", \"switch\", \"num\" ]");//"up": 调高，调大"down": 调低，调小"max": 调到最高，调到最大"min": 调到最低， 调到最小"switch": 切换不同档位"num": 调到指定数值
        RUOQI_DEVICE_ACTIONS_DETAIL.put("temperature", "[ \"up\", \"down\", \"max\", \"min\", \"num\" ]");
    }

    private String marks = "\"";
    private String comma = ",";


    private void save() {
        StringBuffer json_sb = new StringBuffer();
        json_sb.append("{").append("\"deviceId\":").append(marks).append(relationDevice_str).append(marks).append(comma)
                .append("\"name\":").append(marks).append(deviceName.getText().toString()).append(marks).append(comma)
                .append("\"type\":").append(marks).append(deviceType_str).append(marks).append(comma)
                .append("\"actions\": {").append(getActionJson(deviceActions_str)).append("},")
                .append("\"state\": {\"switch\": \"on\"},")
                .append("\"offline\": false,")
                .append("\"roomName\":").append(marks).append(deviceSeat.getText().toString()).append(marks).append(comma).append("}");
        Log.i("info", "获得的json是" + json_sb.toString());

        LocalDb_RuoQiDeviceTable entity = new LocalDb_RuoQiDeviceTable();
        entity.setUuid(relationDevice_str);
        entity.setIs_add(false);
        entity.setName(deviceName.getText().toString());
        entity.setDevice_json(json_sb.toString());
        int result = entity.updateAll("uuid = ?", relationDevice_str);
        if (result == 0) {
            entity.save();
        }
        finish();

    }

    private String getActionJson(String str) {
        StringBuffer result = new StringBuffer();
        if (str != null) {
            String[] arr = str.split(",");
            if (arr != null && arr.length > 0) {
                for (int i = 0; i < arr.length; i++) {
                    result.append(marks).append(arr[i]).append(marks).append(":").append(RUOQI_DEVICE_ACTIONS_DETAIL.get(arr[i])).append(",");

                }
            }
            result.deleteCharAt(result.length() - 1);
        }
        return result.toString();
    }

    private void setView() {
        deviceName = (EditText) findViewById(R.id.activity_ruoqi_adddevice_devicename);
        deviceSeat = (TextView) findViewById(R.id.activity_ruoqi_adddevice_deviceseat);
        deviceType = (TextView) findViewById(R.id.activity_ruoqi_adddevice_devicetype);
        deviceActions = (TextView) findViewById(R.id.activity_ruoqi_adddevice_deviceactions);
        relationDevice = (TextView) findViewById(R.id.activity_ruoqi_adddevice_relationdevice);
        relationDevice_text = (TextView) findViewById(R.id.activity_ruoqi_adddevice_relationdevice_text);
        deviceSeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RuoQi_AddDeviceActivity.this, MyRoomActivity.class);
                startActivityForResult(intent, ConstantConfigure.RUOQI_REQUESTTYPE_DEVICESEAT);
            }
        });
        deviceType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RuoQi_AddDeviceActivity.this, RuoQi_DeviceTypeListActivity.class);
                intent.putExtra("type", ConstantConfigure.RUOQI_REQUESTTYPE_DEVICETYPE);
                startActivityForResult(intent, ConstantConfigure.RUOQI_REQUESTTYPE_DEVICETYPE);

            }
        });
        deviceActions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RuoQi_AddDeviceActivity.this, RuoQi_DeviceTypeListActivity.class);
                intent.putExtra("type", ConstantConfigure.RUOQI_REQUESTTYPE_ACTIONS);
                startActivityForResult(intent, ConstantConfigure.RUOQI_REQUESTTYPE_ACTIONS);
            }
        });
        relationDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (deviceType_str != null &&deviceType_str.equals("scene")) {
                    getMyScenc();
                } else {
                    getMyDevice();
                }
            }
        });
    }

    private void getMyDevice() {
        String method = "mtop.openalink.app.core.devices.getbyuser";
        AlinkHttpUtil.AlinkHttpRequest(method, new HashMap<String, Object>(), new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse != null && transitoryResponse.data != null) {
                    List<WangGuanDeviceEntity> beans = JSON.parseArray((String) transitoryResponse.data, WangGuanDeviceEntity.class);
                    if (beans != null && beans.size() > 0) {
                        Intent intent = new Intent(RuoQi_AddDeviceActivity.this, RuoQi_SubDeviceListActivity.class);
                        intent.putExtra("uuid", beans.get(0).getUuid());
                        startActivityForResult(intent, ConstantConfigure.RUOQI_REQUESTTYPE_RELATIONDEVICE);
                    }
                }

            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
            }
        });
    }

    private void getMyScenc() {
        Intent intent = new Intent(RuoQi_AddDeviceActivity.this, QingJingListActivity.class);
        startActivityForResult(intent, ConstantConfigure.RUOQI_REQUESTTYPE_RELATIONSCENCE);
    }

    private void setSceneView() {
        relationDevice.setText("");
        relationDevice_text.setText("选择场景");
    }

    private void setDeviceView() {
        relationDevice.setText("");
        relationDevice_text.setText("选择设备");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == ConstantConfigure.RESULT_SUCCESS) {
            String result = data.getStringExtra("result");

            switch (requestCode) {
                case ConstantConfigure.RUOQI_REQUESTTYPE_DEVICETYPE:
                    Log.i("info", "获得的结果是" + result);
                    String[] devicetype_arr = result.split(":");
                    if (devicetype_arr != null && devicetype_arr.length == 2) {
                        deviceType.setText(devicetype_arr[1]);
                        deviceType_str = devicetype_arr[0];
                        if (deviceType_str.equals("scene")) {
                            setSceneView();
                        } else {
                            setDeviceView();
                        }
                    }
                    break;
                case ConstantConfigure.RUOQI_REQUESTTYPE_ACTIONS:
                    Log.i("info", "获得的结果是" + result);
                    String[] actions_arr = result.split(",");
                    if (actions_arr != null) {
                        StringBuffer sbForTextView = new StringBuffer();
                        StringBuffer sbForTextView_str = new StringBuffer();
                        for (int i = 0; i < actions_arr.length; i++) {
                            String[] arr = actions_arr[i].split(":");
                            if (arr != null && arr.length == 2) {
                                sbForTextView.append(arr[1]).append(",");
                                sbForTextView_str.append(arr[0]).append(",");
                            }
                        }
                        sbForTextView.deleteCharAt(sbForTextView.length() - 1);
                        deviceActions.setText(sbForTextView.toString());
                        deviceActions_str = sbForTextView_str.toString();
                    }
                    break;
                case ConstantConfigure.RUOQI_REQUESTTYPE_RELATIONDEVICE:
                    Log.i("info", "获得的结果是" + result);
                    String[] relationdevice_arr = result.split(":");
                    if (relationdevice_arr != null && relationdevice_arr.length == 2) {
                        relationDevice.setText(relationdevice_arr[0]);
                        relationDevice_str = relationdevice_arr[1];
                    }
                    break;
                case ConstantConfigure.RUOQI_REQUESTTYPE_RELATIONSCENCE:
                    String name = data.getStringExtra("name");
                    int id = data.getIntExtra("id", 0);
                    relationDevice.setText(name);
                    relationDevice_str = name + ":" + String.valueOf(id);
                    break;
                case ConstantConfigure.RUOQI_REQUESTTYPE_DEVICESEAT:
                    String seat_name = data.getStringExtra("name");
                    deviceSeat.setText(seat_name);
                    break;

            }

        }
    }
}
